package com.leo.ibatis.demo.dao.ibatis;

import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.springframework.util.Assert;

import com.leo.ibatis.demo.criteria.OrdersCriteria;
import com.leo.ibatis.demo.dao.OrdersDao;
import com.leo.ibatis.demo.domain.Orders;
import com.leo.ibatis.demo.util.Paging;

public class OrdersDaoImpl extends SqlMapClientDaoSupport implements OrdersDao {

	public void insert(Orders orders) throws DataAccessException {
		getSqlMapClientTemplate().insert("Orders.insert", orders);
	}

	public int update(Orders orders) throws DataAccessException {
		int actualRowsAffected = 1;

		getSqlMapClientTemplate().update("Orders.update", orders, actualRowsAffected);

		return actualRowsAffected;
	}

	public int delete(int orderid) throws DataAccessException {
		int actualRowsAffected = 1;

		getSqlMapClientTemplate().delete("Orders.delete", new Integer(orderid), actualRowsAffected);

		return actualRowsAffected;
	}

	public Orders select(int orderid) throws DataAccessException {
		return (Orders) getSqlMapClientTemplate().queryForObject("Orders.select", new Integer(orderid));
	}

	@SuppressWarnings("unchecked")
	public List<Orders> list(OrdersCriteria ordersCriteria) throws DataAccessException {
		Assert.notNull(ordersCriteria, "ordersCriteria must not be null");
		
		return getSqlMapClientTemplate().queryForList("Orders.list", ordersCriteria);
	}

	@SuppressWarnings("unchecked")
	public List<Orders> listOnPage(OrdersCriteria ordersCriteria) throws DataAccessException {
		Assert.notNull(ordersCriteria, "ordersCriteria must not be null");
		Assert.notNull(ordersCriteria.getPaging(), "paging must not be null");
		
		int totalResults = count(ordersCriteria);
		Paging paging = ordersCriteria.getPaging();
		paging.setTotalResults(totalResults);
		
		return getSqlMapClientTemplate().queryForList("Orders.list", ordersCriteria, paging.getFirstResult(), paging.getMaxResults());
	}

	public int count(OrdersCriteria ordersCriteria) throws DataAccessException {
		Assert.notNull(ordersCriteria, "ordersCriteria must not be null");
		
		return ((Integer) getSqlMapClientTemplate().queryForObject("Orders.count", ordersCriteria)).intValue();
	}

}
